package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LeetCode16 {

    public static void main(String[] args) {
        LeetCode16 leetCode16 = new LeetCode16();
        System.out.println(leetCode16.threeSumClosest(new int[]{0, 1, 2}, 0));
    }

    public int threeSumClosest(int[] nums, int target) {
        int left, right, sum, closeSum = nums[0] + nums[1] + nums[2];
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            left = i + 1;
            right = nums.length - 1;
            while (left < right) {
                sum = nums[i] + nums[left] + nums[right];
                closeSum = Math.abs(closeSum - target) < Math.abs(sum - target) ? closeSum : sum;
                if (sum < target)
                    left++;
                else if (sum > target) right--;
                else return target;
            }
        }
        return closeSum;
    }
//------------------------------------------------------------------

    public int threeSumClosest1(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length; i++) {
            int start = i + 1, end = nums.length - 1;
            while (start < end) {
                int sum = nums[start] + nums[end] + nums[i];
                if (Math.abs(target - sum) < Math.abs(target - ans))
                    ans = sum;
                if (sum > target)
                    end--;
                else if (sum < target)
                    start++;
                else
                    return ans;
            }
        }
        return ans;
    }
}
